package band.wukong.practice.webservice.kh.sample12;

import org.apache.cxf.binding.soap.SoapMessage;
import org.apache.cxf.binding.soap.interceptor.AbstractSoapInterceptor;
import org.apache.cxf.headers.Header;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.phase.Phase;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Element;
import org.w3c.dom.Node;

import java.util.List;

/**
 * 123123
 *
 * @author wukong(wukonggg@139.com)
 */
public class ServerInboundObjectLicenseInterceptor extends AbstractSoapInterceptor {

    private static final Logger logger = LoggerFactory.getLogger(ServerInboundObjectLicenseInterceptor.class);

    ServerInboundObjectLicenseInterceptor() {
        super(Phase.INVOKE);
    }

    @Override
    public void handleMessage(SoapMessage msg) throws Fault {
        List<Header> headers = msg.getHeaders();
        Object obj;
        for (Header h : headers) {
            logger.debug("h.getUserName() = " + h.getName());
            obj = h.getObject();    // Object是一个Node（Element）
            if (obj instanceof Node) {
                Element ele = (Element) obj;

                Node un;
                Node pn;
                try {
                    un = ele.getElementsByTagName("userName").item(0);
                    pn = ele.getElementsByTagName("password").item(0);
                } catch (NullPointerException e) {
                    throw new RuntimeException("授权无效");
                }
                logger.debug("name = " + un.getTextContent());
                logger.debug("password = " + pn.getTextContent());

                if (!"admin".equals(un.getTextContent()) || !"666".equals(pn.getTextContent())) {
                    throw new RuntimeException("没有授权");
                }
            }
        }
    }
}
